import { login } from '@/api/chat'
import { getToken, setToken, removeToken } from '@/utils/auth'
import {setCookie, getCookie} from "@/utils/support";
import Cookies from "js-cookie";

const user = {
  state: {
    token: getToken(),
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const data = response.data
          const tokenStr = data.token
          setToken(tokenStr)
          setCookie("uid", response.data.userData.id, 15);
          setCookie("nickname", response.data.userData.nickname, 15);
          setCookie("file_path", response.data.userData.file_path, 15);
          commit('SET_TOKEN', tokenStr)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        removeToken()
        Cookies.remove('nickname')
        Cookies.remove('file_path')
        Cookies.remove('nickname')
        Cookies.remove('uid')
        Cookies.remove('password')
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
